import { useState } from 'react';
import ProTable, { ProTableProps } from '@ant-design/pro-table';
import ProForm from '@ant-design/pro-form';
import AdvanceSearch from '@/components/AdvanceSearch/index';
import styles from './index.scss';
import { SearchAndTableProps } from './interface';

export default function SearchAndTable<T, P>(props: SearchAndTableProps<T, P>) {
    const [collapse, setCollapse] = useState(false);
    const [form] = ProForm.useForm();

    const [params, setParams] = useState();

    const dataSourceRequest = (async ({
        pageSize = 10,
        current = 1,
        keyword,
        ...params
    }) => {
        return props.request({ pageSize, current, ...(params as P) });
    }) as ProTableProps<T, P>['request'];

    const finishHandler = async (values: any) => {
        console.log('111');
        setParams(values);
        props.formProps?.onFinish?.(values);
    };
    const formReset = async (values: any) => {
        setParams(values);
        props.formProps?.onReset?.(values);
    };
    return (
        <>
            <AdvanceSearch
                collapse={collapse}
                columns={props.columns}
                otherColumns={props.otherColumns ?? []}
                renderHeader={() => (
                    <ProForm
                        submitter={false}
                        onFinish={finishHandler}
                        form={form}
                        onReset={formReset}
                    >
                        {props.renderCollapseHeader({ collapse, setCollapse })}
                    </ProForm>
                )}
                formProps={{
                    ...props.formProps,
                    onFinish: finishHandler,
                    onReset: formReset,
                }}
            />
            {props.renderController?.()}
            <ProTable<T, P>
                columnEmptyText={false}
                scroll={{ x: 'max-content' }}
                params={params}
                className={styles.tableWrap}
                search={false}
                options={false}
                request={async (params, sort, filter) => {
                    // @ts-ignore
                    return dataSourceRequest(params);
                }}
                columns={props.columns}
                {...props.tableProps}
            />
        </>
    );
}
